/**
 * 时间处理类
 * @author xuej
 */
package com.health.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;



public class DateTimeUtil{

	
	public static Timestamp getDate(Timestamp date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.DATE, 0);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return new Timestamp(cal.getTimeInMillis());
	}
	/**
	 * 20071231转换为2007-12-31
	 * @param date
	 * @return
	 */
	public static String date8(String date){
		if(null==date)return null;
		date = date.trim();
		if(date.length()!=8)return date;
		else return date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6,8);
	}
	/**
	 * 200803转换为2008-03
	 * @param date
	 * @return
	 */
	public static String date6(String date){
		if(null==date)return null;
		date = date.trim();
		if(date.length()!=6)return date;
		else return date.substring(0,4)+"-"+date.substring(4,6);	
	}
	/**
	 * 122221转换成12:22:21
	 * @param time
	 * @return
	 */
	public static String time6(String time){
		if(null==time)return null;
		time = time.trim();
		if(time.length()!=6)return time;
		else return time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
	}
	/**
	 * 122221123456转换成12-22-21 12:34:56
	 * 
	 * @param time
	 * @return
	 */
	public static String time14(String time) {
		if (null == time)
			return null;
		time = time.trim();
		if (time.length() != 14)
			return time;
		else
			return time.substring(0, 4) + "-" + time.substring(4, 6) + "-"
					+ time.substring(6, 8) + " " + time.substring(8, 10) + ":"
					+ time.substring(10, 12) + ":" + time.substring(12, 14);
	}
	/**
	 * 格式化时间(DATE 转 STRING )
	 * @param date
	 * @return
	 */
	public static String formatDateToString(Date date,String formatStr){
		
		return new SimpleDateFormat(formatStr).format(date);
	}
	/**
	 * 格式化时间(DATE 转 STRING yyyyMMdd)
	 * @param date
	 * @return
	 */
	public static String formatDateToString(Date date){
		
		String s = new SimpleDateFormat("yyyyMMdd").format(date);
		return s;
	}
	/**
	 * 格式化时间(DATE 转 STRING yyyy-MM-dd HH:mm:ss)
	 * @param date
	 * @return
	 */
	public static String formatDateToStringWithSeconds(Date date){
		String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		return s;
	}
	/**
	 * 格式化时间(Timestamp 转 STRING yyyy-MM-dd HH:mm:ss)
	 * @param date
	 * @return
	 */
	public static String formatDateToStringWithSeconds(Timestamp date){
		String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		return s;
	}
	/**
	 * 将日期格式的字符串转换为日期
	 * @param dateStr 源日期字符串（yyyy-MM-dd格式）
	 */
	public static Date formatStringToDate(String dateStr) throws Exception{
		if(null==dateStr||("").equals(dateStr))return null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		
		Date date = format.parse(dateStr);
		return date;
	}
	/**
	 * 将日期格式的字符串转换为日期
	 * @param dateStr 源日期字符串
	 * @param formatStr 源日期字符串格式
	 */
	public static Date formatStringToDate(String dateStr,String formatStr) throws Exception{
		if(null==dateStr||("").equals(dateStr))return null;
		if(null==formatStr||("").equals(formatStr)){
			return formatStringToDate(dateStr);
		}
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		Date date = format.parse(dateStr);
		return date;
	}
	/**
	 * 将日期格式的字符串格式化成指定的日期格式
	 * @param dateStr 源日期字符串
	 * @param formatStr1 源日期字符串日期格式
	 * @param formatStr2 新日期字符串日期格式
	 */
	public static String formatDateStringToString(String dateStr,String formatStr1,String formatStr2) throws Exception{
		if(null==dateStr)return null;
		SimpleDateFormat format = new SimpleDateFormat(formatStr1);
		Date date = format.parse(dateStr);
		return new SimpleDateFormat(formatStr2).format(date);

	}
	
	
	/**
	 * 将字符串转换为时间戳Timestamp
	 * @param dateStr yyyy-MM-dd格式
	 * @return
	 * @throws Exception
	 */
	
	public static Timestamp formatStringToTimestamp(String dateStr)throws Exception{
		if(null==dateStr||("").equals(dateStr))return null; 
		return new Timestamp(DateTimeUtil.formatStringToDate(dateStr).getTime());
	}
	/**
	 * 将字符串转换为时间戳Timestamp
	 * @param dateStr yyyy-MM-dd格式
	 * @return
	 * @throws Exception
	 */
	
	public static Timestamp formatStringToTimestamp(String dateStr,String formatStr)throws Exception{
		if(null==dateStr||("").equals(dateStr))return null; 
		return new Timestamp(DateTimeUtil.formatStringToDate(dateStr,formatStr).getTime());
	}
	/**
	 * 将时间戳Timestamp转换成字符串yyyyMMdd格式
	 * @param date
	 * @return
	 */
    public static String formatTimestampToString(Timestamp date){
    	if(null==date||("").equals(date))return null; 
    	String s = new SimpleDateFormat("yyyyMMdd").format(date);
		return s;
    	
    }
	/**
	 * 格式化时间戳为字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatTimestamp2String(Timestamp date,String format){
		if(null==date)return null;
		if(null==format||("").equals(format))return null;
		return new SimpleDateFormat(format).format(date);
	}
	/**
	 * 获取当月第一天
	 * @param outFormat
	 * @return
	 */
	public static String getFirstDay(String outFormat){
		SimpleDateFormat format = new SimpleDateFormat(outFormat);
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DATE, 1);
		return format.format(cal.getTime());
	}
	
	
	
	/**
	 * 增加日期
	 * @param date 源日期
	 * @parame days 需要增加的天数
	 */
	public static Date addDay(Date date,int days){
		if(null==date)return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
		return cal.getTime();
	}
	/**
	 * 增加日期
	 * @param date 源日期（时间戳）
	 * @parame days 需要增加的天数
	 */
	public static Timestamp addDay(Timestamp date,int days){
		if(null==date)return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
		return new Timestamp(cal.getTime().getTime());
	}
	
	/**
	 * 增加日期
	 * @param date 源日期
	 * @parame days 需要增加的月数
	 */
	public static Date addMonth(Date date,int months){
		if(null==date)return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, months);
		return cal.getTime();
	}
	/**
	 * 获得当前日期前的最近n个月的日期最大数
	 * @param dateStr 起始日期
	 * @param formatStr 日期格式
	 * @param months 最近月数n
	 * @return
	 * @throws Exception
	 */
	public static String getCurrentMonths(String formatStr,int months)throws Exception{
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -(months-1));
		cal.set(Calendar.DATE,1);
		return DateTimeUtil.formatDateToString(cal.getTime(),formatStr);
	}

	public static Map<String,String> getBetweenDate2(String startDate,String endDate,String formatStr)throws Exception{
		Date now = new Date();
		Map<String,String> retMap = new HashMap<String,String>();
		String nowStr = DateTimeUtil.formatDateToString(now, formatStr);
		String minStr = DateTimeUtil.getCurrentMonths(formatStr, 3);//获取起始日期的最小日期 3个月
		if((null==startDate||"".equals(startDate))&&(null==endDate||"".equals(endDate))){//起止日期都为空，返回起始日期指定为最近3个月的第一天，终止日期为null
			retMap.put("startDate", minStr);
		}else if(null==startDate||"".equals(startDate)){//如果未指定起始日期，但指定了终止日期
			retMap.put("startDate", minStr);
			if(endDate.compareTo(nowStr)<=0){//如果终止日期在当前日期之前				
				retMap.put("endDate", endDate);
			}
			return retMap;
		}else if(null==endDate||"".equals(endDate)){//如果未指定终止日期，但指定了起始日期，
			if(startDate.compareTo(minStr)<0){//如果起始日期被指定，但为3个月前，强制指定为最近3个月的第一天，终止日期为空
				startDate = minStr;
			}
			retMap.put("startDate", startDate);
		}else{//同时指定了起始日期和终止日期
			if(startDate.compareTo(minStr)<0){//如果起始日期被指定，但为3个月前，强制指定为最近3个月的第一天，终止日期为空
				startDate = minStr;
			}
			retMap.put("startDate", startDate);
			if(endDate.compareTo(nowStr)<=0){//如果终止日期在当前日期之前				
				retMap.put("endDate", endDate);
			}
		}
		
		return retMap;
		
		
	}
	public static Map<String,Timestamp> getBetweenDate2Timestamp(String startDate,String endDate,String formatStr)throws Exception{
		Map<String,String> temp = getBetweenDate2( startDate, endDate,formatStr);
		
		Map<String,Timestamp> retMap = new HashMap<String,Timestamp>();
		retMap.put("startDate", DateTimeUtil.formatStringToTimestamp(temp.get("startDate"), formatStr));
		if(null!=temp.get("endDate")){
			Date _endDate = DateTimeUtil.formatStringToDate(temp.get("endDate"),formatStr);
			String _endDate2 = DateTimeUtil.formatDateToString(_endDate, "yyyy-MM-dd");
			_endDate2 +=" 23:59:59.999";
			retMap.put("endDate", DateTimeUtil.formatStringToTimestamp(_endDate2, "yyyy-MM-dd HH:mm:ss.SSS"));
		}else{
			retMap.put("endDate", null);
		}
		
		return retMap; 
	}
	
	/**
	 * 不限制日期区间
	 * @param startDate
	 * @param endDate
	 * @param formatStr
	 * @return
	 * @throws Exception
	 */
	public static Map<String,String> getBetweenDate2ForMobileFee(String startDate,String endDate,String formatStr)throws Exception{
		Date now = new Date();
		Map<String,String> retMap = new HashMap<String,String>();
		String nowStr = DateTimeUtil.formatDateToString(now, formatStr);
		if(!(null==startDate||"".equals(startDate))){
			retMap.put("startDate", startDate);	
		}
		if(!(null==endDate||"".equals(endDate))){
			if(endDate.compareTo(nowStr)<=0){//如果终止日期在当前日期之前				
				retMap.put("endDate", endDate);
			}	
		}
		return retMap;
		
		
	}
	/**
	 *    分解日期时间段字符串为
	 *    允许查询的时间区间起止日期，未指定起止日期，默认限制为当前1个月
	 * @param dateStr 起始日期终止日期字符串，如20070801_20080101
	 * @param formatStr 日期格式
	 * @return 返回包含起始日期、终止日期的Map对象，key分别为 startDate,endDate
	 * @throws Exception
	 */
	public static Map<String,String> getBetweenDate(String dateStr,String formatStr)throws Exception{
		String[] platDate = new String[]{null,null};
		if(null!=dateStr&&!("").equals(dateStr)){
			String[] temp = dateStr.split("_");
			switch(temp.length) {
			case 0:
				break;
			case 1:
				platDate[0]=temp[0];
				break;
			case 2:
				platDate[0]=temp[0];
				platDate[1]=temp[1];
				break;
			}
		
		}
		return getBetweenDate2(platDate[0],platDate[1],formatStr);
		//return getBetweenDate2("20060101",null,formatStr);
		
	}
	public static Map<String,Timestamp> getBetweenTimestamp(String dateStr,String formatStr)throws Exception{
		String[] platDate = new String[]{null,null};
		if(null!=dateStr&&!("").equals(dateStr)){
			String[] temp = dateStr.split("_");
			switch(temp.length) {
			case 0:
				break;
			case 1:
				platDate[0]=temp[0];
				break;
			case 2:
				platDate[0]=temp[0];
				platDate[1]=temp[1];
				break;
			}
		
		}
		return getBetweenDate2Timestamp(platDate[0],platDate[1],formatStr);
		//return getBetweenDate2("20060101",null,formatStr);
		
	}
	public static Map<String,String> getBetweenDateForMobileFee(String dateStr,String formatStr)throws Exception{
		String[] platDate = new String[]{null,null};
		if(null!=dateStr&&!("").equals(dateStr)){
			String[] temp = dateStr.split("_");
			switch(temp.length) {
			case 0:
				break;
			case 1:
				platDate[0]=temp[0];
				break;
			case 2:
				platDate[0]=temp[0];
				platDate[1]=temp[1];
				break;
			}
		
		}
		return getBetweenDate2ForMobileFee(platDate[0],platDate[1],formatStr);
		//return getBetweenDate2("20060101",null,formatStr);
		
	}
	/**
	 * 通过起始日期、终止日期字符串，获取动态月份表名后缀
	 * @param startDate 起始日期字符串
	 * @param endDate 终止日期字符串
	 * @param inFormatStr 输入日期格式
	 * @param outFormatStr 输出日期格式
	 * @return
	 * @throws Exception
	 */
	public static List<String> getMonthList(String startDate ,String endDate,String inFormatStr,String outFormatStr)throws Exception{
		if(outFormatStr.indexOf("d")!=-1)throw new Exception("getMonthList方法只能输出到月");
		Date dt1 = formatStringToDate(startDate, inFormatStr);
		Date dt2 = formatStringToDate(endDate, inFormatStr);
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt1);
		cal.set(Calendar.DATE, 1);
		dt1 = cal.getTime();
		cal.setTime(dt2);
		cal.set(Calendar.DATE, 1);
		dt2 = cal.getTime();
		List<String> retList = new ArrayList<String>();
		retList.add(formatDateToString(dt1, outFormatStr));
		while(dt1.compareTo(dt2)<0){
			dt1 = addMonth(dt1, 1);
			retList.add(formatDateToString(dt1, outFormatStr));
		}
		return retList;
	}
	
	/**yyMMddhh
	 * 得到系统当前年月日小时分秒数据字符串
	 * @return 返回格式 yyMMddhh ,String 类型
	 * @exception 得到系统当前年月日小时分秒数据字符串错误
	 */
	 public static String getYYMMDDHH(){
		 	
	    	String strYMDHMS="";
	    	Date currentDateTime = new Date();
	    	SimpleDateFormat formatter = new SimpleDateFormat ("yyMMddhh");
	        strYMDHMS= formatter.format(currentDateTime);
	    	return  strYMDHMS; 
	 }
	 
	 
	 
	 /**
		 * 得到系统当前年月日小时分秒数据字符串
		 * @return 返回格式 yyMMddhh ,String 类型
		 * @exception 得到系统当前年月日小时分秒数据字符串错误
		 */
		 public static String getHHMMSS(){
		    	String retS="";
		    	Date currentDateTime = new Date();
		        SimpleDateFormat formatter = new SimpleDateFormat ("hh:mm:ss");
		        retS= formatter.format(currentDateTime);
		    	return  retS; 
		 }
	
	
	/**
	 * 得到系统当前年月日小时分秒数据字符串
	 * @return strYMDHMS 返回的结果，格式 yyyyMMddHHmmss，String 类型
	 * @exception 得到系统当前年月日小时分秒数据字符串错误
	 */
	 public static String getYMDHMS(){
	    	String strYMDHMS="";
	    	Date currentDateTime = new Date();
	        SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMddHHmmss");
	        strYMDHMS= formatter.format(currentDateTime);
	    	return  strYMDHMS; 
	 }
		/**
		 * 获取当月第一天
		 * 
		 * @param date
		 * @return
		 */
		public static Timestamp getFirstDay(Timestamp date) {
			if (null == date)
				return null;
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.set(Calendar.DATE, 1);
			cal.set(Calendar.AM_PM,1);
			cal.set(Calendar.HOUR, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			return new Timestamp(cal.getTime().getTime());
		}
		/**
		 * 增加日期 日期的格式为yyyyMMdd
		 * @param oldDateString
		 * @return
		 */
	    public static String getNewDate(String oldDateString,int days){
	        
	        Date oldDate = changeToDate(oldDateString);
	        Date newDate = addDay(oldDate, days);
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	        return dateFormat.format(newDate); 
	    }
	    
	    public static Date changeToDate(String dateString){
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	        Date date = null;
	        try {
	             date = dateFormat.parse(dateString);
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	        
	        return date;
	    }
	    /**
	     * 获取一个月份的第一天 月份的格式为yyyy-MM
	     * @param year
	     * @param month
	     * @return
	     */
	    public static String getFirstDayOftheMonth(String platMonth){
	    	int year = new Integer(platMonth.substring(0, 4)).intValue();
	    	int month = new Integer(platMonth.substring(5, 7)).intValue();
	        Calendar cal = Calendar.getInstance();
	        cal.set(year, month-1, 1);
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	        return dateFormat.format(cal.getTime());
	    }
	    /**
	     * 获取一个月份的最后一天 月份的格式为yyyy-MM
	     * @param year
	     * @param month
	     * @return
	     */
	    public static String getLastDayOftheMonth(String platMonth){
	    	int year = new Integer(platMonth.substring(0, 4)).intValue();
	    	int month = new Integer(platMonth.substring(5, 7)).intValue();
	        Calendar cal = Calendar.getInstance();
	        cal.set(year, month, 0);
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	        return dateFormat.format(cal.getTime());
	    }
	    /**
	     * 获取当前日期
	     * @return
	     */
	    public static Map getReqDate(){
	    	Date date = new Date();
	    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
	    	SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");
	        Map map = new HashMap();
	        map.put("DATE", dateFormat.format(date));
	        map.put("TIME", timeFormat.format(date));
	    	return map;
	    }
	    /**
	     * 根据订单日期获取订单表号
	     * @param orderDate
	     * @return
	     */
	    public static int getWYOrderTableNumByOrderDate(String orderDate) {
	    	int result = 0;
	    	String startDate = "20080101";
	    	int dayCount = 0;
	    	try {
	    	    dayCount = (int) getCompareDate(startDate, orderDate);
	    	    result = dayCount % 4;
	    	} catch (ParseException e) {
	    	    e.printStackTrace();
	    	}
	    	return result;
	        }
	    
	    /**
	     * 比较起止日期，用于网银获取表名
	     * @param startDate
	     * @param endDate
	     * @return
	     * @throws ParseException
	     */
	    public static long getCompareDate(String startDate, String endDate)throws ParseException {
	       SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
	       Date date1 = formatter.parse(startDate);
	       Date date2 = formatter.parse(endDate);
	       long l = date2.getTime() - date1.getTime();
	       long d = l / (24 * 60 * 60 * 1000);
	       return d;
    }
	    public static void main(String [] args)throws Exception{
	    	/*System.out.println(DateTimeUtil.getBetweenDate2ForMobileFee(null, "20081029", "yyyyMMdd"));
	    	System.out.println(DateTimeUtil.getBetweenDate2("20070121", "20081012", "yyyyMMdd"));*/
	    	System.out.println(getYYMMDDHH());
	    	System.out.println(getYYMMDDHH());
	    	//System.out.println(getYMDHMS().substring(8));
	    	
	    	
//	    	System.out.println(DateTimeUtil.getReqDate().get("DATE"));
//	    	System.out.println(DateTimeUtil.getReqDate().get("TIME"));
//	    	String str="123456#130225198303033322";
//	    	System.out.println(str.substring(0, str.indexOf("#")));
//	    	System.out.println(formatStringToTimestamp("20081003 00:00:00:000", "yyyyMMdd HH:mm:ss:S").getTime());
	    	
	    	//System.out.println(formatDateStringToString("2008-10-10","yyyy-MM-dd","yyyy年M月d日"));
	    }
}



